#coding:utf-8
'''
Created on 2015��4��21��

@author: guowu
'''
from PyQt4.QtGui import QGraphicsRectItem, QTransform, QColor, QGraphicsView,\
    QGraphicsScene, QGraphicsPixmapItem, QFrame, QPixmap, QApplication, QPen,QWidget
from PyQt4.QtSvg import QGraphicsSvgItem
import math
import random
import sys
'''
/****************************************************************************
**
** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies).
** Contact: Qt Software Information (qt-info@nokia.com)
**
** This file is part of the Graphics Dojo project on Qt Labs.
**
** This file may be used under the terms of the GNU General Public
** License version 2.0 or 3.0 as published by the Free Software Foundation
** and appearing in the file LICENSE.GPL included in the packaging of
** this file.  Please review the following information to ensure GNU
** General Public Licensing requirements will be met:
** http://www.fsf.org/licensing/licenses/info/GPLv2.html and
** http://www.gnu.org/copyleft/gpl.html.
**
** If you are unsure which license is appropriate for your use, please
** contact the sales department at qt-sales@nokia.com.
**
** This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE
** WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
**
****************************************************************************/
'''
#include <QtCore>
from PyQt4.QtCore import QObject, QStringList,Qt, SIGNAL, QTimeLine, QPointF,\
    QTime
#include <QtGui>
#include <QtSvg>

#if defined (Q_OS_SYMBIAN)
#include "sym_iap_util.h"
#include <eikenv.h>
#include <eikappui.h>
#include <aknenv.h>
#include <aknappui.h>
#endif

PAGE_COUNT = 5


# class NaviBar : public QObject, public QGraphicsRectItem
# {
#     Q_OBJECT
# 
# public:
#     NaviBar();
# 
#     void setPageOffset(qreal ofs);
# 
# signals:
#     void pageSelected(int page);
# 
# protected:
#     void mousePressEvent(QGraphicsSceneMouseEvent *event);
#     void paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget = 0);
# 
# private:
#     QList<QGraphicsSvgItem*> m_icons;
#     QGraphicsRectItem *m_cursor;
# };

ICON_SIZE = 50
ICON_PAD = 4


class MyObject(QGraphicsRectItem,QObject):
    def __init__(self,parent=None):
        QGraphicsRectItem.__init__(self,parent)
        QObject.__init__(self, parent)

class NaviBar(MyObject):
    def __init__(self,parent=None):
#         QGraphicsRectItem.__init__(self,parent)
#         OOO.__init__(self, parent)
        
        super(NaviBar,self).__init__(parent)
        #super(QObject,self).__init__(parent)
        
        #self.emit(SIGNAL(""))
        self.setRect(0, 0, 5 * ICON_SIZE, ICON_SIZE)
        self.setPen(QPen(Qt.NoPen))
        
        self.m_icons = []
        #self.m_cursor = QGraphicsRectItem()
        
        names = QStringList()
        names << "map" << "web" << "home" << "weather" << "contacts"
        print names[1]
        #for (int i = 0; i < names.count(); ++i)
        for i in range(0,names.count()):
            fname = names[i]
            fname.prepend("icons/")
            fname.append("-page.svg")
            icon = QGraphicsSvgItem(fname)
            icon.setParentItem(self)
            dim = ICON_SIZE - ICON_PAD * 2
            sw = float(dim / icon.boundingRect().width())
            sh = float(dim / icon.boundingRect().height())
            icon.setTransform(QTransform().scale(sw, sh))
            icon.setZValue(2)
            self.m_icons.append(icon)
    
        self.m_cursor = QGraphicsRectItem()
        self.m_cursor.setParentItem(self)
        self.m_cursor.setRect(0, 0, ICON_SIZE, ICON_SIZE)
        self.m_cursor.setZValue(1)
        self.m_cursor.setPen(QPen(Qt.NoPen))
        self.m_cursor.setBrush(QColor(Qt.white))
        self.m_cursor.setOpacity(0.6)

    def setPageOffset(self, ofs):
    
        self.m_cursor.setPos(ofs * ICON_SIZE, 0)
        #for (int i = 0; i < m_icons.count(); ++i)
        for i in range(0,len(self.m_icons)):
            if i == int(ofs + 0.5):
                y = ICON_PAD
            else:
                y = ICON_PAD * 2
            #y = (i == static_cast<int>(ofs + 0.5)) ? ICON_PAD : ICON_PAD * 2
            self.m_icons[i].setPos(i * ICON_SIZE + ICON_PAD, y)
            self.m_icons[i].setOpacity(1)
        
        
    

    #def mousePressEvent(QGraphicsSceneMouseEvent *event):
    def mousePressEvent(self,event):
        return
        #emit pageSelected(static_cast<int>(event->pos().x() / ICON_SIZE))
        self.emit(SIGNAL("pageSelected"),int(event.pos().x() / ICON_SIZE))
    

    #def paint(QPainter * painter, const QStyleOptionGraphicsItem *option, QWidget *widget):
    def paint(self,painter,option, widget):
        painter.setBrush(Qt.white)
        painter.setOpacity(0.2)
        painter.drawRect(option.rect.adjusted(-20, ICON_PAD, 20, 0))


class ParallaxHome(QGraphicsView):
    def __init__(self,parent=None):
        super(ParallaxHome,self).__init__(parent)
        self.m_scene = QGraphicsScene()
        self.m_naviBar = NaviBar()
        self.m_wallpaper = QGraphicsPixmapItem()
        self.m_pageAnimator = QTimeLine()
        self.m_pageOffset = -2
        self.m_items = []
        self.m_positions = []
#     ParallaxHome(QWidget *parent = 0)
#             : QGraphicsView(parent)
        #m_pageOffset(-2) {

        self.setupScene()
        self.setScene(self.m_scene)
        self.setHorizontalScrollBarPolicy(Qt.ScrollBarAlwaysOff)
        self.setVerticalScrollBarPolicy(Qt.ScrollBarAlwaysOff)
        self.setFrameShape(QFrame.NoFrame)
        self.setWindowTitle("Parallax Home")

        self.connect(self.m_pageAnimator, SIGNAL("frameChanged(int)"), self.shiftPage)
        self.m_pageAnimator.setDuration(500)
        self.m_pageAnimator.setFrameRange(0, 100)
        self.m_pageAnimator.setCurveShape(QTimeLine.EaseInCurve)

        self.pageChanged(self.m_pageOffset)


    def pageChanged(self,page):
        page = int(page)


    def slideRight(self): 
        if (self.m_pageAnimator.state() != QTimeLine.NotRunning):
            return
        edge = -(self.m_pageOffset - 1)
        if (edge < PAGE_COUNT):
            self.slideBy(-1)

    def slideLeft(self): 
        if (self.m_pageAnimator.state() != QTimeLine.NotRunning):
            return
        if (self.m_pageOffset < 0):
            self.slideBy(1)
    

    def slideBy(self,dx):
        print self.m_pageOffset,dx
        start = self.m_pageOffset * 1000
        end = (self.m_pageOffset + dx) * 1000
        print start,end
        self.m_pageAnimator.setFrameRange(start, end)
        self.m_pageAnimator.start()

    def choosePage(self,page):
        print page
        if (self.m_pageAnimator.state() != QTimeLine.NotRunning):
            print "00000000"
            return
        if (int(-self.m_pageOffset) == page):
            print "1111111111"
            return
        print "2222222"
        self.slideBy(-page - self.m_pageOffset)


    def shiftPage(self,frame):
        print "frame000000000000000000000000000000",frame
        ww = self.width()
        hh = self.height() - self.m_naviBar.rect().height()

        oldPage = int(-self.m_pageOffset)
        self.m_pageOffset = float(frame) / float(1000)
        print self.m_pageOffset
        newPage = int(-self.m_pageOffset)
        print newPage
        self.m_naviBar.setPageOffset(-self.m_pageOffset)
        if (oldPage != newPage):
            print "old=new",newPage
            self.pageChanged(newPage)

        ofs = self.m_pageOffset * ww
        #for (int i = 0; i < m_items.count(); ++i) {
        for i in range(len(self.m_items)):
            pos = self.m_positions[i]
            xy = QPointF(pos.x() * ww, pos.y() * hh)
            #print xy
            #self.m_items[i].setPos(xy + QPointF(ofs, 0))
            self.m_items[i].setPos(QPointF(10, 10))

        center = self.m_wallpaper.pixmap().width() / 2
        parallax = 3
        base = center - (ww / 2) - (PAGE_COUNT >> 1) * (ww / parallax)
        wofs = base - self.m_pageOffset * ww / parallax
        self.m_wallpaper.setPos(-wofs, 0)
        #self.m_items[0].setPos(-wofs, 0)


    def resizeEvent(self,event):
        #return
        #Q_UNUSED(event)
        self.layoutScene()

    def keyPressEvent(self,event):
        if (event.key() == Qt.Key_Right):
            self.slideRight()
        if (event.key() == Qt.Key_Left):
            self.slideLeft()
        event.accept()


    def layoutScene(self):

        ww = self.width()
        hh = self.height()

        self.m_scene.setSceneRect(0, 0, PAGE_COUNT * ww - 1, hh - 1)
        self.centerOn(ww / 2, hh / 2)

        nw = self.m_naviBar.rect().width()
        nh = self.m_naviBar.rect().height()
        self.m_naviBar.setPos((ww - nw) / 2, hh - nh)

        self.shiftPage(self.m_pageOffset * 1000)

    def setupScene(self):

        #math.qsrand(QTime.currentTime().second())
        
        names = QStringList()
        names << "brownies" << "cookies" << "mussels" << "pizza" << "sushi"
        names << "chocolate" << "fish" << "pasta" << "puding" << "trouts"

        #for (int i = 0; i < PAGE_COUNT * 2; ++i) {
        for i in range(0,PAGE_COUNT*2):
            fname = names[i]
            fname.prepend("images/")
            fname.append(".jpg")
            print fname
            pixmap = QPixmap(fname)
            pixmap = pixmap.scaledToWidth(200)
            item = QGraphicsPixmapItem(self.m_scene.addPixmap(pixmap))
            self.m_items.append(item)

            x = float((i >> 1) + (random.randint(0,30)) / 100.0)
            y = float((i & 1) / 2.0  + (random.randint(0,20)) / 100.0)
            print x,y
            self.m_positions.append(QPointF(x, y))
            item.setZValue(1)

        #m_naviBar = NaviBar()
        self.m_scene.addItem(self.m_naviBar)
        self.m_naviBar.setZValue(2)
        #self.connect(self.m_naviBar, SIGNAL("pageSelected"), self.choosePage)
        self.choosePage(-2)

        self.m_wallpaper = self.m_scene.addPixmap(QPixmap("icons/surfacing.png"))
        self.m_wallpaper.setZValue(0)

        self.m_scene.setItemIndexMethod(QGraphicsScene.NoIndex)


#include "parallaxhome.moc"

if __name__ == "__main__":

    app = QApplication(sys.argv)

    w = ParallaxHome()
#if defined(Q_OS_SYMBIAN)
    #w.showMaximized()
    #w.show()
    #lock orientation
#     CAknAppUi* appUi = dynamic_cast<CAknAppUi*>(CEikonEnv::Static()->AppUi());
#     if (appUi)
#         appUi->SetOrientationL(CAknAppUi::EAppUiOrientationPortrait);
# #else
    w.resize(350, 504)
    w.show()
#endif

    app.exec_()

